Advanced Array Visualizer

Create, Read, Update, Delete, and Search array elements with stunning animations

Array is Empty

Add some elements to get started!

Array Length
0
First Element
-
Last Element
-
Sum of Elements
0
Product of Elements
1
Mode (Most Frequent)
-
Total Operations
0
Memory Address
-

Array Operations

Extends array while preserving existing elements
Demonstrates cloning by modifying a copy without affecting original
Demonstrates shallow copy by modifying objects that affect both arrays
Apply mathematical operations to every element in the array
Automatically reshapes 1D array to optimal 2D matrix
Creates array with random positive and negative numbers
Automatically rotates array if needed, then finds smallest element
Sorts the array using in-place merge sort algorithm with detailed visualization
Sort array using only prefix flips (reverse from index 0 to k)
Sort array such that nums[0] < nums[1] > nums[2] < nums[3]...
Sorts only the specified subarray range
Leave indices empty to fill entire array
Apply mathematical functions to all array elements
Calculates trigonometric functions for each element (in radians)
Delete element and shift all subsequent elements left
Find maximum sum of any contiguous subarray of length k
Find longest subarray with sum ≤ target
Group array elements into intervals for histogram analysis
Find maximum/minimum sum of k consecutive elements
Sort array containing only 0s, 1s, and 2s using three-pointer technique
Rearranges sorted array as: max, min, 2nd max, 2nd min, ...
Find all contiguous subarrays with product less than k
Find minimum swaps to group all elements ≤ K together
Find elements that are greater than all elements to their right
Find element that appears more than n/2 times
Find index where sum of left elements equals sum of right elements
Calculate Greatest Common Divisor and Least Common Multiple
Identify prime numbers (green) and composite numbers (red) in the array
Equilibrium Point Algorithm

An equilibrium point is an index in the array where the sum of elements on the left equals the sum of elements on the right.

function findEquilibrium(arr) {
  let totalSum = arr.reduce((a, b) => a + b, 0);
  let leftSum = 0;
  for (let i = 0; i < arr.length; i++) {
    let rightSum = totalSum - leftSum - arr[i];
    if (leftSum === rightSum) {
      return i; // Equilibrium found
    }
    leftSum += arr[i];
  }
  return -1; // No equilibrium point
}
Step 1: Calculate total sum of all elements
Step 2: Initialize left sum to 0
Step 3: For each index i, calculate right sum = total sum - left sum - arr[i]
Step 4: If left sum equals right sum, return current index
Step 5: Otherwise, add current element to left sum and continue
Step 6: If no equilibrium found, return -1
Data Binning Algorithms
Binning by Number of Intervals:
function binByCount(arr, numBins) {
  const minVal = Math.min(...arr);
  const maxVal = Math.max(...arr);
  const range = maxVal - minVal;
  const binSize = range / numBins;
  const bins = Array(numBins).fill(0).map(() => []);
  
  for (let value of arr) {
    const binIndex = Math.min(
      Math.floor((value - minVal) / binSize),
      numBins - 1
    );
    bins[binIndex].push(value);
  }
  return bins;
}
Binning by Fixed Width:
function binByWidth(arr, width) {
  const minVal = Math.min(...arr);
  const maxVal = Math.max(...arr);
  const numBins = Math.ceil((maxVal - minVal) / width);
  const bins = Array(numBins).fill(0).map(() => []);
  
  for (let value of arr) {
    const binIndex = Math.min(
      Math.floor((value - minVal) / width),
      numBins - 1
    );
    bins[binIndex].push(value);
  }
  return bins;
}
Step 1: Calculate data range (min, max values)
Step 2: Determine bin intervals based on method
Step 3: Assign each element to appropriate bin
Step 4: Count elements in each bin and display distribution
Find maximum distance (j-i) where arr[i] == arr[j] and i < j
Find maximum AND and OR pairs in the array
Move all zero elements to front or end while maintaining relative order of non-zero elements
Find subarray whose sum is closest to zero
Move all negative values to the front while maintaining relative order
Move all even numbers to the front while maintaining relative order
Negate every element of a mutable numeric sequence
Sliding Window Algorithms
Fixed-size Window:
function maxSumFixedWindow(arr, k) {
  let maxSum = 0, currentSum = 0;
  // Calculate first window
  for (let i = 0; i < k; i++) {
    currentSum += arr[i];
  }
  maxSum = currentSum;
  // Slide the window
  for (let i = k; i < arr.length; i++) {
    currentSum += arr[i] - arr[i - k];
    maxSum = Math.max(maxSum, currentSum);
  }
  return maxSum;
}
Variable-size Window:
function longestSubarraySumLeq(arr, target) {
  let left = 0, currentSum = 0, maxLength = 0;
  for (let right = 0; right < arr.length; right++) {
    currentSum += arr[right];
    while (currentSum > target && left <= right) {
      currentSum -= arr[left];
      left++;
    }
    maxLength = Math.max(maxLength, right - left + 1);
  }
  return maxLength;
}
Dutch National Flag Algorithm (Three-Pointer Technique)

Sorts an array containing only 0s, 1s, and 2s in a single pass using three pointers:

function dutchNationalFlagSort(arr) {
  let low = 0, mid = 0, high = arr.length - 1;
  while (mid <= high) {
    switch (arr[mid]) {
      case 0: // Found 0
        [arr[low], arr[mid]] = [arr[mid], arr[low]];
        low++; mid++;
        break;
      case 1: // Found 1
        mid++;
        break;
      case 2: // Found 2
        [arr[mid], arr[high]] = [arr[high], arr[mid]];
        high--;
        break;
    }
  }
  return arr;
}
Pointer Roles:
Low: Tracks the boundary for 0s (everything before low is 0)
Mid: Current element being processed (everything between low and mid-1 is 1)
High: Tracks the boundary for 2s (everything after high is 2)
Time Complexity: O(n) - Single pass through the array
Space Complexity: O(1) - In-place sorting
Ugly Number Problems
An ugly number is a positive number whose prime factors are only 2, 3, and 5
Find the n-th number whose prime factors are only 2, 3, and 5
Find the n-th number whose prime factors are from given prime list
Ugly Number Results

Results will appear here

Detect special mathematical numbers in the array
Convert Excel column titles (A, AB, ZY) to column numbers
Convert column numbers to Excel column titles (1→A, 28→AB, 701→ZY)
Create an ordered stream and insert values at specific indices
Find all sequences of consecutive numbers that sum to target
Randomly select an element based on weights using Cumulative Weights method
Uses array elements as center coordinates and radius
Ugly Number Algorithms
Ugly Number Check:
function isUgly(num) {
  if (num <= 0) return false;
  while (num % 2 === 0) num /= 2;
  while (num % 3 === 0) num /= 3;
  while (num % 5 === 0) num /= 5;
  return num === 1;
}
Nth Ugly Number (Dynamic Programming):
function nthUglyNumber(n) {
  let ugly = [1];
  let i2 = 0, i3 = 0, i5 = 0;
  for (let i = 1; i < n; i++) {
    let next = Math.min(ugly[i2]*2, ugly[i3]*3, ugly[i5]*5);
    ugly.push(next);
    if (next === ugly[i2]*2) i2++;
    if (next === ugly[i3]*3) i3++;
    if (next === ugly[i5]*5) i5++;
  }
  return ugly[n-1];
}
Super Ugly Number:
function superUglyNumber(n, primes) {
  let ugly = [1];
  let indices = Array(primes.length).fill(0);
  for (let i = 1; i < n; i++) {
    let next = Math.min(...primes.map((p, j) => ugly[indices[j]] * p));
    ugly.push(next);
    primes.forEach((p, j) => {
      if (next === ugly[indices[j]] * p) indices[j]++;
    });
  }
  return ugly[n-1];
}
Abbreviation must be alphanumeric (e.g., w3b4j9)
Split array into k subarrays to minimize the largest sum
Count subarrays with exactly k distinct integers
Find the longest subarray where comparison signs alternate between elements
Count pairs (i, j) where i < j and nums[i] > 2 * nums[j]
Analyze local and global inversions with step-by-step visualization
Find minimum arrows to burst overlapping balloons (intervals)
Generate Gray code where successive numbers differ by exactly one bit
Binary search to find smallest divisor where sum of ceil(arr[i]/divisor) ≤ threshold
Find minimum eating speed to finish all bananas within given hours
Find the first bad version in [G, G, ..., B, B, ...] array
Maximum sum of non-adjacent elements with DP visualization
Greedy algorithm for the NP-hard Shortest Superstring problem
Find elements that appear once when others appear multiple times
Solve circular route gas station problem
Count subarrays with exactly k odd numbers
Partition array such that every element in left <= every element in right
Partition array into subarrays of length at most k to maximize sum
Partition string where each character appears in only one partition
Check if array can be split into three contiguous parts with equal sum
Enter strings as JSON array and choose delimiter
Game theory: Can the first player force a win?
String Operations Algorithms
Encode/Decode Strings:
def encode(strs):
  if not strs: return ""
  encoded = []
  for s in strs:
    encoded.append(f"{len(s)}#{s}")
  return "".join(encoded)

def decode(s):
  if not s: return []
  res = []
  i = 0
  while i < len(s):
    delimiter_idx = s.find('#', i)
    length = int(s[i:delimiter_idx])
    i = delimiter_idx + 1
    res.append(s[i:i + length])
    i += length
  return res
Koko Eating Bananas Algorithm

Koko wants to eat all bananas in h hours. Each pile has a different number of bananas. Koko can eat k bananas per hour from any pile. Find the minimum k such that Koko can eat all bananas within h hours.

Algorithm Steps:
function minEatingSpeed(piles, h):
  left = 1, right = max(piles)
  while left < right:
    mid = (left + right) // 2
    hours_needed = 0
    for pile in piles:
      hours_needed += ceil(pile / mid)
    if hours_needed <= h:
      right = mid // Try smaller speed
    else:
      left = mid + 1 // Need larger speed
  return left
Example:
piles = [3, 6, 7, 11], h = 8
k = 4 → hours = ceil(3/4)+ceil(6/4)+ceil(7/4)+ceil(11/4) = 1+2+2+3 = 8 ✓
k = 3 → hours = ceil(3/3)+ceil(6/3)+ceil(7/3)+ceil(11/3) = 1+2+3+4 = 10 ✗
Minimum k = 4
Step 1: Initialize binary search range [1, max(pile)]
Step 2: Test middle speed k
Step 3: Calculate total hours needed for speed k
Step 4: If hours ≤ h, k is valid → search lower half
Step 5: If hours > h, k is invalid → search upper half
Step 6: Repeat until left = right
Reorder Log Files:
def reorderLogFiles(logs):
  def transform(log):
    idx = log.find(' ')
    identifier, content = log[:idx], log[idx+1:]
    if content[0].isdigit():
      return (1, )
    else:
      return (0, content, identifier)
  logs.sort(key=transform)
  return logs
Find maximum sum of contiguous subarray allowing at most one element deletion
Find the longest chain of pairs where b < c in [a,b] and [c,d]
Find all arithmetic subarrays with at least 3 elements
Calculate number of ways to decode a numeric string to letters (A=1, B=2... Z=26)
Check if array can be partitioned into two subsets with equal sum
Check if a string can be segmented into dictionary words
Find maximum subarray sum no larger than K
Visualizes LRU Cache with array + hash map. Press Shift+R to reset.
Visualizes Least Frequently Used (LFU) Cache Algorithm
Decode Ways Algorithm

Counts the number of ways to decode a string of digits to letters using mapping: A=1, B=2, ..., Z=26.

function numDecodings(s) {
  if (!s || s[0] == '0') return 0;
  let n = s.length;
  let dp = new Array(n+1).fill(0);
  dp[0] = 1; // empty string
  dp[1] = 1; // first digit
  for (let i = 2; i <= n; i++) {
    let single = parseInt(s[i-1]);
    let twoDigit = parseInt(s.substring(i-2, i));
    if (single != 0) dp[i] += dp[i-1];
    if (10 <= twoDigit <= 26) dp[i] += dp[i-2];
  }
  return dp[n];
}
Rules:
  • A digit 1-9 can be decoded as A-I
  • Two digits 10-26 can be decoded as J-Z
  • '0' cannot be decoded alone
  • '0' can only appear as part of 10 or 20
Examples:
  • "12" → 2 ways: "AB" (1,2) or "L" (12)
  • "226" → 3 ways: "BBF" (2,2,6), "BZ" (2,26), "VF" (22,6)
  • "06" → 0 ways (starts with 0)
Arithmetic Slices Algorithm

An arithmetic slice is a contiguous subarray with at least 3 elements where the difference between consecutive elements is constant.

function numberOfArithmeticSlices(nums) {
  if (nums.length < 3) return 0;
  let count = 0;
  let currentLength = 2;
  for (let i = 2; i < nums.length; i++) {
    if (nums[i] - nums[i-1] == nums[i-1] - nums[i-2]) {
      currentLength++;
      count += (currentLength - 2);
    } else {
      currentLength = 2;
    }
  }
  return count;
}
Example: For array [1, 2, 3, 4]
- Arithmetic slices: [1,2,3], [2,3,4], [1,2,3,4]
- Total: 3 slices
LeetCode Problem 1186: Maximum Subarray Sum with One Deletion

Given an array of integers, return the maximum sum of a contiguous subarray (possibly empty) after deleting at most one element from the array.

def maximumSum(arr):
  """
  Given an array of integers, return the maximum sum of a subarray
  with at most one element deletion.
  Time: O(n), Space: O(n)
  """
  n = len(arr)
  if n == 0: return 0
  if n == 1: return arr[0]

  # forward[i]: max subarray sum ending at i
  forward = [0] * n
  forward[0] = arr[0]
  for i in range(1, n):
    forward[i] = max(arr[i], forward[i-1] + arr[i])

  # backward[i]: max subarray sum starting at i
  backward = [0] * n
  backward[n-1] = arr[n-1]
  for i in range(n-2, -1, -1):
    backward[i] = max(arr[i], backward[i+1] + arr[i])

  # Option 1: No deletion (standard Kadane's algorithm)
  max_no_deletion = max(forward)

  # Option 2: With one deletion
  max_with_deletion = float('-inf')
  for i in range(1, n-1):
    # Delete element at i, connect forward[i-1] and backward[i+1]
    max_with_deletion = max(max_with_deletion, forward[i-1] + backward[i+1])

  return max(max_no_deletion, max_with_deletion)
# Optimized version with O(1) space
def maximumSumOptimized(arr):
  """Optimized version with O(1) space using DP states."""
  dp0 = arr[0] # max sum ending at i with 0 deletions
  dp1 = 0 # max sum ending at i with 1 deletion
  res = arr[0]

  for i in range(1, len(arr)):
    # With 1 deletion: either delete current element (dp0)
    # or we've already deleted before (dp1 + arr[i])
    dp1 = max(dp0, dp1 + arr[i])

    # With 0 deletions: standard Kadane
    dp0 = max(arr[i], dp0 + arr[i])

    res = max(res, dp0, dp1)

  return res
Algorithm Explanation
Step 1: Calculate forward maximum subarray sums (Kadane's algorithm from left)
Step 2: Calculate backward maximum subarray sums (Kadane's algorithm from right)
Step 3: For each element (except first and last), calculate sum of forward[i-1] + backward[i+1]
Step 4: Compare with no-deletion maximum and return the maximum of both
Time Complexity: O(n) where n is array length
Space Complexity: O(n) for DP arrays, O(1) for optimized version
Investment Analysis Toolkit

Professional financial metrics for informed investment decisions

💡 Business Context: Enter historical stock prices to analyze investment performance, volatility, and returns.
Day-to-day percentage changes
Continuous compounding returns
Total return from start to each point
Overall investment performance
Daily price movements & volatility
N-day price momentum
ROC percentage indicator
Opening gap calculations
Daily trading performance
SMA - Average price over period
EMA - Weighted average
MACD - Trend momentum
Signal line for MACD
Bollinger Middle Band
Bollinger Upper Band
Key Metrics Explained
Daily Returns: Essential for understanding short-term volatility and daily performance
Log Returns: Used in financial modeling for time-series analysis and risk management
Cumulative Returns: Shows investment growth trajectory over time
Total Return: Overall investment performance measurement
Price Differences: Reveals daily price movements and market volatility patterns
Set Operations Algorithms
Union of Arrays:
function unionArrays(arrays) {
  let unionSet = new Set();
  for (let arr of arrays) {
    for (let element of arr) {
      unionSet.add(element);
    }
  }
  return Array.from(unionSet);
}
Intersection of Arrays:
function intersectionArrays(arrays) {
  if (arrays.length === 0) return [];
  let intersection = arrays[0];
  for (let i = 1; i < arrays.length; i++) {
    intersection = intersection.filter(
      element => arrays[i].includes(element)
    );
  }
  return [...new Set(intersection)];
}
Solve famous Leetcode array problems with visualizations
Enter a string containing only curly braces {} to validate parentheses
Uses binary search to find first and last occurrence in sorted array
Determine if you can reach the last index starting from first index
Find maximum profit from daily stock prices (LeetCode #121)
// Add this in the algorithm explanation section
Best Time to Buy and Sell Stock Algorithm

Find the maximum profit by buying low and selling high. You can only make one transaction.

function maxProfit(prices) {
  let minPrice = Infinity;
  let maxProfit = 0;
  for (let i = 0; i < prices.length; i++) {
    if (prices[i] < minPrice) {
      minPrice = prices[i];
    } else if (prices[i] - minPrice > maxProfit) {
      maxProfit = prices[i] - minPrice;
    }
  }
  return maxProfit;
}
Step 1: Initialize minPrice to infinity and maxProfit to 0
Step 2: Iterate through each day's price
Step 3: Update minPrice if current price is lower
Step 4: Calculate potential profit and update maxProfit if higher
Step 5: Return the maximum profit found
Find days until warmer temperature for each day
Calculate sum of elements from start to end index (inclusive)
Given a collection of intervals, merge all overlapping intervals
For each element, count how many elements to the right are smaller
Find the length of the longest substring without repeating characters
Longest Substring Without Repeating Characters Algorithm
function lengthOfLongestSubstring(s) {
  let maxLength = 0;
  let start = 0;
  let charMap = new Map();
  
  for (let end = 0; end < s.length; end++) {
    if (charMap.has(s[end]) && charMap.get(s[end]) >= start) {
      start = charMap.get(s[end]) + 1;
    }
    charMap.set(s[end], end);
    maxLength = Math.max(maxLength, end - start + 1);
  }
  return maxLength;
}
Algorithm Steps:
Step 1: Initialize start pointer, maxLength, and character map
Step 2: Iterate through string with end pointer
Step 3: If duplicate found within current window, move start pointer
Step 4: Update character's last seen position
Step 5: Update maxLength if current window is longer
Step 6: Return maxLength when iteration completes
Find maximum fruits you can pick with two baskets
Convert array to non-decreasing using Greedy + Prefix Sum approach
Calculate span values using monotonic stack approach
Calculate maximum rectangular area in histogram using stack
Rearranges array into lexicographically next greater permutation
Two Sum Algorithm

Find all pairs of indices where the sum of elements equals the target.

function twoSum(arr, target) {
  let pairs = [];
  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i] + arr[j] === target) {
        pairs.push([i, j]);
      }
    }
  }
  return pairs;
}
Trapping Rain Water:

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

function trap(height) {
  let left = 0, right = height.length - 1;
  let leftMax = 0, rightMax = 0;
  let water = 0;
  while (left < right) {
    if (height[left] < height[right]) {
      leftMax = Math.max(leftMax, height[left]);
      water += leftMax - height[left];
      left++;
    } else {
      rightMax = Math.max(rightMax, height[right]);
      water += rightMax - height[right];
      right--;
    }
  }
  return water;
}
Stock Span Problem Algorithm

The stock span problem calculates for each day, the number of consecutive days (including current day) for which the stock price was less than or equal to the current day's price.

function calculateStockSpan(prices) {
  let spans = new Array(prices.length);
  let stack = []; // monotonic stack (decreasing order)
  
  for (let i = 0; i < prices.length; i++) {
    // Pop while stack is not empty and top <= current
    while (stack.length > 0 && prices[stack[stack.length-1]] <= prices[i]) {
      stack.pop();
    }
    // Calculate span
    spans[i] = stack.length === 0 ? i + 1 : i - stack[stack.length-1];
    // Push current index to stack
    stack.push(i);
  }
  return spans;
}
Key Points:
• Uses a monotonic stack (decreasing order of prices)
• Time Complexity: O(n) - each element pushed and popped once
• Space Complexity: O(n) for the stack
Visualize advanced sorting algorithms with step-by-step animations
Advanced Sorting Algorithms
Selection Sort:
function selectionSort(arr) {
  let n = arr.length;
  for (let i = 0; i < n-1; i++) {
    let minIdx = i;
    for (let j = i+1; j < n; j++) {
      if (arr[j] < arr[minIdx]) {
        minIdx = j;
      }
    }
    [arr[i], arr[minIdx]] = [arr[minIdx], arr[i]];
  }
  return arr;
}
Measures research impact based on citation counts
Insertion Sort:
function insertionSort(arr) {
  let n = arr.length;
  for (let i = 1; i < n; i++) {
    let key = arr[i];
    let j = i - 1;
    while (j >= 0 && arr[j] > key) {
      arr[j+1] = arr[j];
      j--;
    }
    arr[j+1] = key;
  }
  return arr;
}
Selection Sort Steps:
• Find the minimum element in the unsorted portion
• Swap it with the first element of the unsorted portion
• Move the boundary between sorted and unsorted portions one element to the right
• Repeat until the entire array is sorted
Insertion Sort Steps:
• Start with the second element as the key
• Compare the key with elements in the sorted portion to its left
• Shift elements greater than the key one position to the right
• Insert the key in its correct position
• Repeat for all elements
Operation Log